package app;
import info.clearthought.layout.TableLayout;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.Caret;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Buscar extends javax.swing.JDialog {

	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private JPanel jPanel1;
	private JTextField txtReemplazar;
	private JButton reempAll;
	private JCheckBox comienzo;
	private JLabel reempLabel;
	private JLabel buscarLabel;
	private JButton reempBtn;
	private JButton cerrar;
	private JButton buscarBtn;
	private JTextField buscar;
	private Main main;

	/**
	* Auto-generated main method to display this JDialog
	*/
		
	public Buscar(JFrame frame) {
		super(frame);
		initGUI();
		this.setAlwaysOnTop(true);
		this.setTitle("Buscar");
		addEscapeKey();

	}
	
	private void addEscapeKey ()
	{
	// Handle escape key to close the dialog

	KeyStroke escape = KeyStroke.getKeyStroke (KeyEvent.VK_ESCAPE, 0, false);
	Action escapeAction = new AbstractAction ()
	{
	/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

	public void actionPerformed (ActionEvent e)
	{
	buscar.setText("");
	txtReemplazar.setText("");
	dispose ();
	}
	};

	getRootPane ().getInputMap (JComponent.WHEN_IN_FOCUSED_WINDOW).put (escape, "ESCAPE");
	getRootPane ().getActionMap ().put ("ESCAPE", escapeAction);
	}
	
	
	
	
	
	
	
	
	
	
	public void conectar(Main m) {
		main=m;
	}
	
	
	
	public void init() {
		buscar.setText(""); 
		String textoABuscar = main.getEditorSelectedText();
		 buscar.setText(textoABuscar);
		 txtReemplazar.setText("");
		 comienzo.setSelected(false);
		 reempBtn.setEnabled(false);
		 buscar.requestFocus();
	

	}
	
	
	public void reemplazar() {
		 String textoABuscar = buscar.getText();
		 
		 String textoAReemplazar= txtReemplazar.getText();
		 
		 if (textoAReemplazar== null) textoAReemplazar="";
		 if (textoABuscar==null) textoABuscar="";
		 
		 if (textoABuscar != "")
	        {
	        
		  textoABuscar=textoABuscar.toLowerCase();
	        // Se obtiene el texto del JTextArea.
	        String texto = main.getEditorText();
	        
	        if (texto.length()!=0 &&  textoABuscar.length()!=0) {
	        
	      
	        
	        texto=texto.toLowerCase();
	        int posicion = 0;
	        while (posicion >=0) {
	        
	      
	        posicion = texto.indexOf(textoABuscar, posicion);
	        // Si no se encuentra el texto, se termina.
	        if (posicion == -1)
	        {
	        	
	            return;
	            
	        }
	       
	        main.setEditorCaretPosition(posicion);
	        main.moveEditorCaretPosition(posicion + textoABuscar.length());
	        main.editorReplaceSelection(textoAReemplazar);
	        posicion=posicion+1;
	        }
	        }
	        }
	}
	
	private boolean checkForWholeWord(int check, String text, int add, int caret){
		int offsetLeft=(caret+add) -1;
		int offsetRight=(caret+add)+check;
		if( (offsetLeft <0)||(offsetRight >text.length()) ) return true;
		return ((! Character.isLetterOrDigit(text.charAt(offsetLeft)) )&&
		(! Character.isLetterOrDigit(text.charAt(offsetRight)) ));
		}
	/**
	* replaceAll replaces the search word with the new word selected by the user
	* @see #checkForWholeWord(int, String, int, int)
	*/
	private void replaceAll(){
		String word = buscar.getText();
		String text = main.getEditorText();
		String insert = txtReemplazar.getText();
		StringBuffer sb = new StringBuffer(text);
		int diff = insert.length()-word.length();
		int offset=0;
		int tally=0;
		for(int i=0; i<text.length()-word.length(); i++){
		String temp = text.substring(i, i+word.length());
		if( (temp.equals(word))&&(checkForWholeWord(word.length(), text, 0, i)) ){
		tally++;
		sb.replace(i+offset, i+offset+word.length(), insert);
		offset+=diff;
		}// if equals(word)
		}// for
		main.setEditorText((sb.toString() ));
		//endResultMessage(true, tally);
		//MainEditor.textPane.setCaretPosition(0);
		}
		/**
		* endResultMessage replaces the search word with the new word selected by the user
		* @param boolean isReplaceAll: whether this was a replace or a Find search
		* @param int tally: how many words were replaced in
		* @see #replaceAll()
		* @see #statusInfo
		*/
	
	
	private void buscar() {
		 String textoABuscar = buscar.getText();
		 if (textoABuscar == null)
	        {
	            textoABuscar = "";
	        }
		 
		
		   textoABuscar=textoABuscar.toLowerCase();
		 
	        // Se obtiene el texto del JTextArea.
	        String texto = main.getEditorText();
	        texto=texto.toLowerCase();
	     
	        Caret seleccion = main.getEditorCaret();
	        int posicion = 0;
	      
	       if (seleccion.getDot() != seleccion.getMark())
	        {
	    	  
	            posicion = seleccion.getDot();
	           
	        }
	        else
	        	
	        	posicion=main.getEditorCaretPosition();
	        	
	        		        
	        if (comienzo.isSelected()) posicion=0;
	        // Se busca el texto a partir de la posición del texto seleccionado si lo
	        // habia
	        
	        posicion = texto.indexOf(textoABuscar, posicion);

	        // Si no se encuentra el texto, se termina.
	        if (posicion == -1)
	        {
	        	reempBtn.setEnabled(false);
	            return;
	            
	        }
	        else
	        
	        	reempBtn.setEnabled(true);
	        
	        
	        main.setEditorCaretPosition(posicion);
	        main.moveEditorCaretPosition(posicion + textoABuscar.length());
	        comienzo.setSelected(false);
	        
	        
		
	}
	
	
	private void initGUI() {
		try {
			{
				jPanel1 = new JPanel();
				getContentPane().add(jPanel1, BorderLayout.CENTER);
				TableLayout jPanel1Layout = new TableLayout(new double[][] {{7.0, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, 7.0}, {7.0, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, 7.0}});
				jPanel1Layout.setHGap(5);
				jPanel1Layout.setVGap(5);
				jPanel1.setLayout(jPanel1Layout);
				jPanel1.setBackground(new java.awt.Color(255,255,255));
				jPanel1.setPreferredSize(new java.awt.Dimension(507, 227));
				{
					buscar = new JTextField();
					jPanel1.add(buscar, "1, 2, 3, 2");
				}
				{
					txtReemplazar = new JTextField();
					jPanel1.add(txtReemplazar, "1, 4, 3, 4");
					

				}
				{
					buscarBtn = new JButton(new ImageIcon(Main.class.getResource("find.png")));
					jPanel1.add(buscarBtn, "4,2,c,f");
					buscarBtn.setText("Buscar");
					
					buscarBtn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "play");
					buscarBtn.getActionMap().put("play", new AbstractAction() {
					private static final long serialVersionUID = 1L;
					public void actionPerformed(ActionEvent e) {
						buscar();  // some function
					}
					});
					
					
					
					
					buscarBtn.setBackground(new java.awt.Color(255,255,255));
					buscarBtn.setFont(new java.awt.Font("Ubuntu",0,12));
					buscarBtn.setToolTipText("Buscar");
					buscarBtn.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							buscarBtnActionPerformed(evt);
						}
					});
				}
				{
					cerrar = new JButton();
					jPanel1.add(cerrar, "4,6,c,f");
					cerrar.setText("Cerrar");
					cerrar.setBackground(new java.awt.Color(255,255,255));
					cerrar.setFont(new java.awt.Font("Ubuntu",0,12));
					cerrar.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							cerrarActionPerformed(evt);
						}
					});
				}
				{
					reempBtn = new JButton();
					jPanel1.add(reempBtn, "4, 4, c, f");
					reempBtn.setText("Reemplazar");
					reempBtn.setBackground(new java.awt.Color(255,255,255));
					reempBtn.setFont(new java.awt.Font("Ubuntu",0,12));
					reempBtn.setToolTipText("Reemplazar");
					reempBtn.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							reempBtnActionPerformed(evt);
						}
					});
				}
				{
					buscarLabel = new JLabel();
					jPanel1.add(buscarLabel, "1, 1");
					buscarLabel.setText("Buscar");
					buscarLabel.setFont(new java.awt.Font("Ubuntu",0,13));
				}
				{
					reempLabel = new JLabel();
					jPanel1.add(reempLabel, "1, 3");
					reempLabel.setText("Reemplazar");
					reempLabel.setFont(new java.awt.Font("Ubuntu",0,13));
				}
				{
					comienzo = new JCheckBox();
					jPanel1.add(comienzo, "2, 1, 3, 1");
					comienzo.setText("Desdel el comienzo");
					comienzo.setBackground(new java.awt.Color(255,255,255));
					comienzo.setFont(new java.awt.Font("Ubuntu",0,13));
				}
				{
					reempAll = new JButton();
					jPanel1.add(reempAll, "4,5,c,f");
					reempAll.setText("Reemplazar todo");
					reempAll.setBackground(new java.awt.Color(255,255,255));
					reempAll.setFont(new java.awt.Font("Ubuntu",0,12));
					reempAll.setToolTipText("Reemplazar todo");
					reempAll.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent evt) {
							reempAllActionPerformed(evt);
						}
					});
				}
			}
			this.setSize(543, 260);
			this.setIconImage(new ImageIcon(getClass().getClassLoader().getResource("app/postinga16x16.png")).getImage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	private void buscarBtnActionPerformed(ActionEvent evt) {
	buscar();
	main.editorRequestFocus();
	}
	
	private void cerrarActionPerformed(ActionEvent evt) {
		this.dispose();
		main.requestEditorFocus();
	}
	
	private void reempBtnActionPerformed(ActionEvent evt) {
		 main.editorReplaceSelection(txtReemplazar.getText());
		 reempBtn.setEnabled(false);
	}
	
	
	private void reemplazarTodo(){
	replaceAll();
	}
	
	
	private void reempAllActionPerformed(ActionEvent evt) {
	reemplazarTodo();
	}

}
